package drds.server.net.packet;

import java.io.UnsupportedEncodingException;

import drds.server.config.ErrorCode;

/**
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class PacketUtil {
	private static final String CODE_PAGE_1252 = "Cp1252";

	public static final ResultSetHeaderPacket getHeader(int fieldCount) {
		ResultSetHeaderPacket resultSetHeaderPacket = new ResultSetHeaderPacket();
		resultSetHeaderPacket.packetId = 1;
		resultSetHeaderPacket.fieldCount = fieldCount;
		return resultSetHeaderPacket;
	}

	public static byte[] encode(String string, String charset) {
		if (string == null) {
			return null;
		}
		try {
			return string.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			return string.getBytes();
		}
	}

	public static final FieldPacket getFieldPacket(String name, String orgName, int type) {
		FieldPacket fieldPacket = new FieldPacket();
		fieldPacket.name = encode(name, CODE_PAGE_1252);
		fieldPacket.type = (byte) type;
		return fieldPacket;
	}

	public static final FieldPacket getFieldPacket(String name, int type) {
		FieldPacket fieldPacket = new FieldPacket();
		fieldPacket.name = encode(name, CODE_PAGE_1252);
		fieldPacket.type = (byte) type;
		return fieldPacket;
	}

	public static final ErrorPacket getShutdown() {
		ErrorPacket errorPacket = new ErrorPacket();
		errorPacket.packetId = 1;
		errorPacket.errorNo = ErrorCode.ER_SERVER_SHUTDOWN;
		errorPacket.errorMessage = "The server has been shutdown".getBytes();
		return errorPacket;
	}

	public static final FieldPacket getFieldPacket(BinaryPacket binaryPacket, String fieldName) {
		FieldPacket fieldPacket = new FieldPacket();
		fieldPacket.read(binaryPacket);
		fieldPacket.name = encode(fieldName, CODE_PAGE_1252);
		fieldPacket.packetLength = fieldPacket.computePacketSize();
		return fieldPacket;
	}

}